<template>
  <div :class="{ 'has-logo': showLogo }">
    <logo v-if="showLogo" :collapse="isCollapse" />
    <el-scrollbar wrap-class="scrollbar-wrapper" v-if="permissionStore.menuLoaded">
      <!-- 菜单容器 - 匹配原型分组设计 -->
      <nav class="menu-nav" :class="{ collapsed: isCollapse }">
        <!-- 主导航分组 -->
        <div class="menu-group" v-if="!isCollapse">
          <div class="menu-group-title">主导航</div>
        </div>
        
        <el-menu
          :default-active="activeMenu"
          :collapse="isCollapse"
          :background-color="variables.menuBg"
          :text-color="variables.menuText"
          :unique-opened="true"
          :active-text-color="variables.menuActiveText"
          :collapse-transition="false"
          mode="vertical"
          class="main-menu"
        >
          <menu-item
            v-for="menu in mainMenus"
            :key="menu.id || menu.path"
            :menu="menu"
          />
        </el-menu>

        <!-- 分隔线和扩展功能分组 -->
        <template v-if="extensionMenus.length > 0">
          <div class="menu-separator" v-if="!isCollapse"></div>
          
          <div class="menu-group" v-if="!isCollapse">
            <div class="menu-group-title">扩展功能</div>
          </div>
          
          <el-menu
            :default-active="activeMenu"
            :collapse="isCollapse"
            :background-color="variables.menuBg"
            :text-color="variables.menuText"
            :unique-opened="true"
            :active-text-color="variables.menuActiveText"
            :collapse-transition="false"
            mode="vertical"
            class="extension-menu"
          >
            <menu-item
              v-for="menu in extensionMenus"
              :key="menu.id || menu.path"
              :menu="menu"
            />
          </el-menu>
        </template>
      </nav>
    </el-scrollbar>
  </div>
</template>

<script setup lang="ts">
import { computed, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useAppStore } from '@/stores/app'
import { usePermissionStore } from '@/stores/permission'
import Logo from './Logo.vue'
import MenuItem from './MenuItem.vue'
// import variables from '@/styles/variables.scss'

const variables = {
  menuBg: 'var(--sidebar-bg)',
  menuText: 'var(--sidebar-text)',
  menuActiveText: 'var(--sidebar-text-active)'
}

const route = useRoute()
const appStore = useAppStore()
const permissionStore = usePermissionStore()

// 计算属性
const routes = computed(() => permissionStore.sidebarMenus)

// 菜单分组逻辑 - 只明确定义扩展功能，其余默认为主导航
const extensionMenus = computed(() => {
  const allRoutes = routes.value || []
  
  // 扩展功能：明确指定哪些菜单属于扩展功能（根据原型页面）
  const extensionKeywords = [
    '数据分析', 'analytics', 'chart', 'report', '报表', '统计',
    '消息中心', 'message', 'notification', '通知', '消息',
    '日志管理', 'log', 'logs', '日志',
    '监控中心', 'monitor', 'monitoring', '监控'
  ]
  
  return allRoutes.filter(menu => {
    const menuName = (menu.title || menu.name || '').toLowerCase()
    const menuPath = (menu.path || '').toLowerCase()
    
    // 如果菜单名称或路径包含扩展功能关键词，则归入扩展功能
    return extensionKeywords.some(keyword => 
      menuName.includes(keyword.toLowerCase()) || 
      menuPath.includes(keyword.toLowerCase())
    )
  })
})

const mainMenus = computed(() => {
  const allRoutes = routes.value || []
  const extensionMenuIds = new Set(extensionMenus.value.map(m => m.id))
  
  // 主导航：除了扩展功能以外的所有菜单都归入主导航
  return allRoutes.filter(menu => !extensionMenuIds.has(menu.id))
})

// 详细日志：侧边栏菜单变更
if (import.meta.env.MODE !== 'production') {
  watch(routes, (val) => {
    console.log('[Sidebar] routes updated, count:', Array.isArray(val) ? val.length : 'N/A')
    if (Array.isArray(val) && val.length > 0) {
      console.log('[Sidebar] first menu:', { id: val[0].id, name: val[0].name, title: val[0].title, path: val[0].path })
      console.log('[Sidebar] all menus:', val.map((m: any) => ({ id: m.id, name: m.name, title: m.title })))
    } else {
      console.warn('[Sidebar] ⚠️ routes is empty or not an array!', val)
    }
  }, { immediate: true })
  
  watch(() => permissionStore.menus, (val) => {
    console.log('[Sidebar] permissionStore.menus changed, count:', Array.isArray(val) ? val.length : 'N/A')
    if (Array.isArray(val) && val.length > 0) {
      console.log('[Sidebar] menus data:', val.map((m: any) => ({ id: m.id, name: m.name, title: m.title })))
    }
  }, { immediate: true, deep: true })
}
const showLogo = computed(() => true) // 显示logo
const isCollapse = computed(() => appStore.sidebarCollapsed)
const activeMenu = computed(() => route.path)
</script>

<style lang="scss"></style>

<style lang="scss" scoped></style>
